package rs.etf.es.algorithm.states;

import java.util.ArrayList;

import rs.etf.es.algorithm.Algorithm;
import rs.etf.es.algorithm.AlgorithmState;
import rs.etf.es.algorithm.JTextAreaLogger;
import rs.etf.es.algorithm.Node;
import rs.etf.es.algorithm.NodeAddressBook;

public class SetInitialRootProbabilitiesAndPiValuesState implements AlgorithmState {

    private Algorithm algorithm;

    @Override
    public void performAction() {
	JTextAreaLogger.instance().log("");

	Node root = NodeAddressBook.instance().getRoot();

	for (String value : root.getValues()) {
	    Double initialValue = root.getMyCPT().getProbability(Node.NO_PARENT, value, Node.NO_CONDITION);
	    root.setProbability(value, initialValue);
	    JTextAreaLogger.instance().log("Setting probability on root variable " + root.getName() + " to " + initialValue);
	    root.getPiValues().put(value, root.getProbability(value));
	    JTextAreaLogger.instance().log("Setting pi value for " + value + " in root " + root.getName() + " to " + root.getProbability(value));
	    // AlgorithmBlocker.instance().stopHere();
	}

	ArrayList<Node> children = root.getChildren();
	for (Node child : children) {
	    SendPiMessageState newState = new SendPiMessageState();
	    newState.setSender(root);
	    newState.setReceiver(child);
	    newState.setAlgorithm(algorithm);
	    algorithm.pushAlgorithmState(newState);
	}
    }

    @Override
    public void setAlgorithm(Algorithm algorithmClass) {
	algorithm = algorithmClass;
    }

    public AlgorithmState clone() {
	SetInitialRootProbabilitiesAndPiValuesState newState = new SetInitialRootProbabilitiesAndPiValuesState();
	newState.setAlgorithm(algorithm);
	return newState;
    }

    @Override
    public void refreshNodes() {

    }

}
